package errs

import (
	"gitee.com/baizhige/go-server-tempalte/common/log"
	"gitee.com/baizhige/go-server-tempalte/common/response"
)

type Error struct {
	Code     string `json:"code"`
	Remark   string `json:"remark"`
	Payload  any
	MsgParam map[string]string
}

func (e Error) Error() string {
	return e.Code + ":" + e.Remark
}
func (e Error) ToResponse(platType, language string) response.Response {
	key := platType + "_" + e.Code
	respCode, ok := response.RespMap[key]
	if !ok {
		//输出没有找到错误码
		log.ErrorF("error code do not exist in response map, code: %s", e.Code)
		//展示兜底
		respCode = response.RespCode{Code: e.Code, DefaultMsg: e.Remark}
	}
	resp := respCode.ToRes(language).Body(e.Payload)
	for k, v := range e.MsgParam {
		resp = resp.MsgReplace(k, v)
	}
	return resp
}
func (e Error) Body(data any) Error {
	e.Payload = data
	return e
}

func (e Error) Msg(key, value string) Error {
	e.MsgParam[key] = value
	return e
}

func New(code, remark string) Error {
	e := Error{
		Code:     code,
		Remark:   remark,
		MsgParam: map[string]string{},
	}
	//TODO 注册到数据库
	return e
}
